<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card 内容区 -->
    <el-card>
      <!--搜索添加区域 输入框和添加按钮 el-row el-col 栅格布局 -->
      <el-row :gutter="15">
        <el-col :span="8">
          <el-input @clear="getUserList" clearable v-model="queryInfo.query" placeholder="请输入内容">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="AdddialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域  stripe 隔行变色-->
      <el-table border stripe :data="userlist">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch @change="userStateChange(scope.row)" v-model="scope.row.mg_state"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
                <el-button @click="edit(scope.row.id)" type="primary" size="mini"  icon="el-icon-edit"></el-button>
                <el-button @click='del(scope.row.id)' type="danger" size="mini" icon="el-icon-delete"></el-button>
                <el-tooltip :enterable="false" effect="dark" content="分配角色" placement="top">
                    <el-button @click="setRole(scope.row)" type="warning" size="mini" icon="el-icon-setting"></el-button>
                </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="AdddialogVisible"
        width="50%"
        @close='addDialogClosed'
        >
        <!-- 内容区  带验证的表单-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
        </el-form>
        
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="AdddialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="50%"
  @close="editDialogClose"
  >
  <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="70px" >
    <el-form-item label="用户名" prop="username">
        <el-input disabled v-model="editForm.username"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserIfo">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配角色对话框 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRoledialogVisible"
  width="30%"
  @close="setRoledialogclosed"
  >
  <div>
    <p>当前用户：{{ userinfo.username }}</p>
    <p>当前角色：{{ userinfo.role_name }}</p>
    <P>分配角色：
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in rolelist"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>

    </P>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>

export default {
  data() {
    // 校验邮箱 自定义校验规则
    let checkEmail =(rule,value,cb)=>{
        //    验证邮箱的正则
        const regEmail =/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        if(regEmail.test(value)){
            // 合法
            return cb()
        }
        cb(new Error('请输入合法邮箱'))
    }

    // 校验手机号
    let checkMobile=(rule,value,cb)=>{
    
        const regEmail =/^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if(regEmail.test(value)){
            return cb()
        }
        cb(new Error('请输入合法手机号'))
    }
    return {
      //查询参数  get
      queryInfo: {
        query: '',
        pagenum: 1, //当前页码
        pagesize: 2, //每页显示条数
      },
      userlist: [], //用户列表数据 做表格展示
      total: 0, //用户总数 做分页
      AdddialogVisible:false,//添加用户对话框
      editDialogVisible:false,//编辑用户对话框
    //  添加用户表单对象
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
        

      },
      //编辑表单对象
      editForm:{
      
      },
    //  编辑表单验证规则对象 
      editFormrules:{
        email:[{required:true,message:'请输入邮箱',trigger:'blur'},
        {validator:checkEmail,trigger:'blur'}],
        mobile:[{required:true,message:'请输入手机号',trigger:'blur'}
        ,
        {validator:checkMobile,trigger:'blur'}]
      },
    //   表单验证规则对象
    addFormRules:{
        username:[
            {required:true,message:'请输入用户名',trigger:'blur'}
           ,{min:3,max:6,message:'用户名在3~6位之间',trigger:'blur'}
        ],
        password:[
            {required:true,message:'请输入密码',trigger:'blur'}
           ,{min:6,max:15,message:'密码在6~15位之间',trigger:'blur'}
        ],
        email:[{required:true,message:'请输入邮箱',trigger:'blur'},
        
        {validator:checkEmail,trigger:'blur'}],
        mobile:[{required:true,message:'请输入手机号',trigger:'blur'}
        ,
        
        {validator:checkMobile,trigger:'blur'}]
    },
    setRoledialogVisible:false,//分配角色对话框
userinfo:{},//分配角色的用户信息
rolelist:[],//所有角色列表
selectedRoleId:'',//选中的角色id
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      // 获取信息
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      // console.log(res);
      // 错误处理
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      //    赋值给前端
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 每页大小改变  赋值 重新获取数据
    handleSizeChange(newSize){
        // console.log(newSize);
        this.queryInfo.pagesize=newSize
        this.getUserList()
    },
    // 当前页改变 如 第一页-》第二页
    handleCurrentChange(newPage){
        this.queryInfo.pagenum=newPage
        this.getUserList()
    },
    // 修改用户状态
   async userStateChange(userinfo){
     const {data:res} = await  this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
       if(res.meta.status !==200){
            // 手动取消操作
            userinfo.mg_state=!userinfo.mg_state
          return this.$message.error('更新用户状态失败')
       }
       this.$message.success('更新用户状态成功')
    },
    // 添加对话框关闭
    addDialogClosed(){
        // 重置表单
        this.$refs.addFormRef.resetFields()
    },
    // 确定添加用户
    addUser(){
        this.$refs.addFormRef.validate(async valid=>{
            if(!valid) return this.$message.error('校验失败')
            // 校验成功 进行添加用户操作 网络请求
          const {data:res}  = await this.$http.post('users',this.addForm)
          console.log(res);
            if(res.meta.status !==201){
               return this.$message.error('添加用户失败')
            }
                // 提示成功
            this.$message.success('添加用户成功')
            // 关闭对话框
            this.AdddialogVisible=false
            // 重新获取数据列表
            this.getUserList()

        })
    },
// 编辑用户弹出对话框
  async  edit(id){
        // 编辑的id
        // console.log(id);
    const {data:res}   =await this.$http.get('users/'+id)
    if(res.meta.status !==200){return this.$message.error('查询用户信息失败')}
    this.editForm=res.data
    this.editDialogVisible=true
    },
    // 关闭对话框中重置表单
    editDialogClose(){
       this.$refs.editFormRef.resetFields()
    },
    // 确认修改按钮
    editUserIfo(){
         this.$refs.editFormRef.validate(async valid=>{
            if(!valid) return 
            // 发送网路请求 id 直接从editForm中获取
          const {data:res}  = await this.$http.put('users/'+this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile})
            if(res.meta.status !==200){
               return this.$message.error('修改用户失败')
            }
                // 提示成功
            this.$message.success('修改用户信息成功')
            // 关闭对话框
            this.editDialogVisible=false
            // 重新获取数据列表
            this.getUserList()
         })
        // this.editDialogVisible = false
    },
    // 删除用户对话框
    async  del(id){
        // 删除用户的id
        const confirmResult = await  this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(confirmResult !== 'confirm'){
            return this.$message.info('取消删除')
        }
        // console.log('确认删除');
        const {data:res}= await this.$http.delete('users/'+id)
        if (res.meta.status !== 200) {
            return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        this.getUserList()
    },
    // 分配角色 对话框 显示和数据获取
   async setRole(userinfo){
      this.userinfo=userinfo
      // 获取所有角色列表 供选择
      const { data: res } = await this.$http.get('roles')
      //   console.log(res);
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolelist = res.data
      // console.log(this.rolelist);
      this.setRoledialogVisible=true
    },
    // 确认修改
   async saveRoleInfo(){
       if(!this.selectedRoleId){
        return this.$message.error('请选择分配的角色')
       }
//修改用户角色
      const {data:res}=
      await this.$http.put (`users/${this.userinfo.id}/role`, {rid:this.selectedRoleId})
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('更新角色成功')
      this.setRoledialogVisible=false
      this.getUserList()
    },
    //关闭分配角色对话框
    setRoledialogclosed(){
      // 重置数据
      this.rolelist=[],
      this.userinfo=[],
      this.selectedRoleId=''
    } 
  },
}
</script>
<style lang="less" scoped>
</style>